package com.hllxd.hism.star.basic.service.config.clickhouse;

import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import ru.yandex.clickhouse.ClickHouseConnection;
import ru.yandex.clickhouse.ClickHouseDataSource;
import ru.yandex.clickhouse.ClickHouseStatement;
import ru.yandex.clickhouse.settings.ClickHouseProperties;

import javax.annotation.PostConstruct;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

/**
 * @author xiyong.lxy
 * @date 20210727
 */
@Slf4j
@Component
public class CkClient2 {
    private static final Logger logger = LoggerFactory.getLogger(CkClient2.class);
    private static ClickHouseConnection conn = null;

    @Autowired
    private CkConfig ckConfig;

    @PostConstruct
    public void initCkClient() {
        try {
            ClickHouseProperties clickHouseProperties = new ClickHouseProperties();
            clickHouseProperties.setSocketTimeout(300000);
            clickHouseProperties.setUser(ckConfig.getUser());
            clickHouseProperties.setPassword(ckConfig.getPassword());
            ClickHouseDataSource clickHouseDataSource = new ClickHouseDataSource(ckConfig.getHost(), clickHouseProperties);
            conn = clickHouseDataSource.getConnection();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static ResultSet query(String sql) throws SQLException {
        Statement stmt = conn.createStatement();
        return stmt.executeQuery(sql);
    }

    public void test() throws SQLException {
        ClickHouseConnection conn1 = CkClient2.conn;
        ClickHouseConnection conn2 = CkClient2.conn;
        ClickHouseConnection conn3 = CkClient2.conn;
        ClickHouseConnection conn4 = CkClient2.conn;

        System.out.println(conn1 == conn2);
        System.out.println(conn1 == conn3);
        System.out.println(conn1 == conn4);

        ClickHouseStatement statement1 = conn1.createStatement();
        ClickHouseStatement statement2 = conn2.createStatement();

        System.out.println(statement1 == statement2);
    }
}
